<template>
  <div class="chart-container">
    <!-- 市场情绪指标面板 -->
    <div class="market-sentiment" v-if="marketSentiment?.marketTrend">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>市场趋势</template>
            <div class="sentiment-value" :class="marketSentiment.marketTrend.trend">
              {{ marketSentiment.marketTrend.description }}
              <div class="strength">强度: {{ marketSentiment.marketTrend.strength }}%</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>平均溢价率</template>
            <div class="sentiment-value" :class="getPremiumClass(marketSentiment.avgPremium)">
              {{ marketSentiment.avgPremium }}%
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>平均收益率</template>
            <div class="sentiment-value" :class="getYtmClass(marketSentiment.avgYtm)">
              {{ marketSentiment.avgYtm }}%
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>成交量变化</template>
            <div class="sentiment-value" :class="getVolumeClass(marketSentiment.volumeChange)">
              {{ marketSentiment.volumeChange }}%
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 简化后的图表控制区 -->
    <div class="chart-controls">
      <div class="filter-controls">
        <el-select v-model="priceFilter" placeholder="价格区间">
          <el-option label="全部" value="all"/>
          <el-option label="100元以下" value="under100"/>
          <el-option label="100-120元" value="100to120"/>
          <el-option label="120元以上" value="above120"/>
        </el-select>
      </div>
    </div>
    
    <!-- 买卖点提示 -->
    <div class="trading-signals" v-if="signals.length > 0">
      <el-collapse>
        <el-collapse-item title="交易信号提示">
          <el-timeline>
            <el-timeline-item
              v-for="signal in signals"
              :key="signal.date"
              :type="signal.type === 'success' ? 'success' : 'warning'"
              :timestamp="signal.date"
            >
              {{ signal.message }}
            </el-timeline-item>
          </el-timeline>
        </el-collapse-item>
      </el-collapse>
    </div>

    <v-chart class="chart" :option="priceViewOption" autoresize @click="handleChartClick"/>
  </div>
</template>

<script setup>
import { use } from "echarts/core";
import * as echarts from 'echarts/core';
import { CanvasRenderer } from "echarts/renderers";
import { LineChart, BarChart } from "echarts/charts";
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DataZoomComponent,
  LegendComponent,
  MarkPointComponent,
  VisualMapComponent,
} from "echarts/components";
import VChart, { THEME_KEY } from "vue-echarts";
import http from '@/utils/http';
import { ref, onMounted, provide } from 'vue';
import { ElMessage } from 'element-plus';

// 注册必要的组件
use([
  CanvasRenderer,
  LineChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DataZoomComponent,
  LegendComponent,
  MarkPointComponent,
  VisualMapComponent,
]);

// 提供主题
provide(THEME_KEY, 'light');

// 简化状态管理
const priceFilter = ref('all');
const signals = ref([]);
const marketSentiment = ref(null);

/** 
 * @typedef {Object} BondIndexData
 * @property {string} price_dt - 日期
 * @property {number} price - 指数价格(decimal(12,3))
 * @property {number} mid_price - 中位价格(decimal(12,3))
 * @property {number} avg_ytm_rt - 平均到期收益率(decimal(10,2))
 * @property {number} temperature - 转债温度(decimal(10,2))
 */

const formatValue = (seriesName, value) => {
  if (value === null || value === undefined || !isFinite(value)) return '-';

  switch(seriesName) {
    case '转债等权':
    case '中位价格':
      return value.toFixed(2);
    case '平均YTM':
    case '温度指标':
      return value.toFixed(2) + '%';
    default:
      return value.toFixed(2);
  }
};

// 修改图表配置
const priceViewOption = ref({
  backgroundColor: '#1a233f',
  title: {
    text: '可转债市场综合分析',
    textStyle: { color: '#fff' }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: { type: 'cross' },
    backgroundColor: 'rgba(255,255,255,0.9)',
    formatter: function(params) {
      const date = params[0].axisValue;
      let html = `<div style="font-weight:bold;margin-bottom:5px">${date}</div>`;
      
      params.forEach(param => {
        const value = formatValue(param.seriesName, param.value);
        const dot = `<span style="display:inline-block;width:10px;height:10px;border-radius:50%;background-color:${param.color};margin-right:5px"></span>`;
        html += `<div style="color:${param.color};padding:3px 0">${dot}${param.seriesName}: ${value}</div>`;
      });
      
      return html;
    }
  },
  legend: {
    data: ['转债等权', '中位价格', '平均YTM'],
    textStyle: { color: '#fff' },
    top: 10
  },
  grid: {
    left: '5%',
    right: '5%',
    bottom: '15%',
    top: '15%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLabel: { 
      color: '#fff',
      rotate: 45 
    },
    axisLine: {
      lineStyle: { color: '#fff' }
    }
  },
  yAxis: [
    {
      type: 'value',
      name: '价格',
      position: 'left',
      min: 200,  // 设置最小值
      max: 2600, // 设置最大值
      alignTicks: true,
      axisLabel: { 
        color: '#4ECDC4',
        formatter: '{value}' 
      },
      axisLine: {
        lineStyle: { color: '#4ECDC4' }
      },
      splitLine: {
        lineStyle: { 
          type: 'dashed',
          color: 'rgba(255,255,255,0.1)' 
        }
      }
    },
    {
      type: 'value',
      name: '中位价格',
      position: 'left',
      min: 80,  // 设置最小值
      max: 140, // 设置最大值
      alignTicks: true,
      offset: 60,
      axisLabel: { 
        color: '#FFB75E',
        formatter: '{value}' 
      },
      axisLine: {
        lineStyle: { color: '#FFB75E' }
      },
      splitLine: {
        show: false
      }
    },    
    {
      type: 'value',
      name: '平均YTM',
      position: 'right',
      alignTicks: true,
      min: -16,  // 根据图中所示设置最小值
      max: 8,  // 根据图中所示设置最大值
      axisLabel: { 
        color: '#FF6B6B',
        formatter: '{value}%' 
      },
      axisLine: {
        lineStyle: { color: '#FF6B6B' }
      },
      splitLine: {
        show: false
      }
    }
  ],
  series: [
    {
      name: '转债等权',
      type: 'line',
      yAxisIndex: 0,  // 使用第一个左侧Y轴
      data: [],
      lineStyle: { 
        width: 2,
        color: '#4ECDC4' 
      },
      symbol: 'none'
    },
    {
      name: '中位价格',
      type: 'line',
      yAxisIndex: 1,  // 使用第二个左侧Y轴
      data: [],
      lineStyle: { 
        width: 2,
        color: '#FFB75E' 
      },
      symbol: 'none'
    },
    {
      name: '平均YTM',
      type: 'line',
      yAxisIndex: 2,  // 使用右侧Y轴
      data: [],
      lineStyle: { 
        width: 2,
        color: '#FF6B6B' 
      },
      symbol: 'none'
    }
  ],
  dataZoom: [{
    type: 'slider',
    show: true,
    xAxisIndex: [0],
    start: 0,
    end: 100,
    bottom: '2%',
    height: 20
  }, {
    type: 'inside',
    xAxisIndex: [0]
  }],
  showLoading: true,
});

// 新增辅助函数
const getSeriesColor = (seriesName) => {
  const colors = {
    '转债等权': '#4ECDC4',
    '中位价格': '#FFB75E',
    '平均YTM': '#FF6B6B',
    '温度指标': '#45B7D1'
  };
  return colors[seriesName] || '#999';
};

// 修改数据获取和处理方法
const fetchData = async () => {
  try {
    const stock_list = await http.get('/stock');
    stock_list.sort((a, b) => new Date(a.price_dt) - new Date(b.price_dt));

    const dates = stock_list.map(item => item.price_dt);
    priceViewOption.value.xAxis.data = dates;

    // 更新系列数据
    priceViewOption.value.series[0].data = stock_list.map(item => Number(item.price));
    priceViewOption.value.series[1].data = stock_list.map(item => Number(item.mid_price));
    priceViewOption.value.series[2].data = stock_list.map(item => Number(item.avg_ytm_rt));

  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('数据加载失败');
  } finally {
    priceViewOption.value.showLoading = false;
  }
};

// 获取市场情绪数据
const fetchMarketSentiment = async () => {
  try {
    const response = await http.get('/stock/sentiment');
    if (response && response.marketTrend) {
      marketSentiment.value = response;
    }
  } catch (error) {
    console.error('获取市场情绪数据失败:', error);
  }
};

// 保留必要的工具函数
const handleChartClick = (params) => {
  if (params.componentType === 'series') {
    const data = params.data;
    const date = params.name;
    console.log('点击了数据点:', { date, data });
  }
};

// 市场情绪相关的工具函数
const getPremiumClass = (premium) => {
  if (premium < 20) return 'good';
  if (premium < 40) return 'warning';
  return 'danger';
};

const getYtmClass = (ytm) => {
  if (ytm > 3) return 'good';
  if (ytm > 1) return 'warning';
  return 'danger';
};

const getVolumeClass = (change) => {
  if (change > 20) return 'danger';
  if (change > 0) return 'good';
  return 'warning';
};

onMounted(() => {
  fetchData();
  fetchMarketSentiment();
});
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 800px;
  padding: 20px;
}

.chart-controls {
  margin-bottom: 20px;
  text-align: center;
}

.chart {
  width: 100%;
  height: calc(100% - 40px);
}

.indicator-controls {
  margin-top: 10px;
}

.filter-controls {
  margin-top: 10px;
  display: flex;
  gap: 10px;
  justify-content: center;
}

.alert-container {
  margin: 10px 0;
  max-height: 150px;
  overflow-y: auto;
}

.view-selector {
  margin-bottom: 10px;
}

.market-sentiment {
  margin-bottom: 20px;
}

.sentiment-value {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
}

.sentiment-value.up { color: #67C23A; }
.sentiment-value.down { color: #F56C6C; }
.sentiment-value.stable { color: #909399; }

.sentiment-value.good { color: #67C23A; }
.sentiment-value.warning { color: #E6A23C; }
.sentiment-value.danger { color: #F56C6C; }

.trading-signals {
  margin: 10px 0;
  max-height: 200px;
  overflow-y: auto;
}

.strength {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}
</style>
